﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Text;
using FX.CC.Andon.Entity.BasicDataManage;
using FX.CC.Andon.Utility.Common;
using FX.CC.Andon.Utility.DataBase;

namespace FX.CC.Andon.Service.BasicDataManage
{
    public class ReqHelpService : DbHelperBase
    {
        public int GetReqHelpCount(ReqHelpQcEntity model)
        {
            var strSql = new StringBuilder();
            strSql.Append(" SELECT COUNT(*) AS [count] FROM UT_ReqHelp WHERE WSID=@WSID AND ETypeCode=@ETypeCode ");
            var count = 0;
            using (var cmd = Db.GetSqlStringCommond(strSql.ToString()))
            {
                try
                {
                    Db.AddInParameter(cmd, "@WSID", model.WSID);
                    Db.AddInParameter(cmd, "@ETypeCode", model.ETypeCode);
                    using (IDataReader reader = Db.ExecuteReader(cmd))
                    {
                        if (reader.Read())
                        {
                            count = Convert.ToInt32(reader["count"]);
                        }
                    }

                }
                catch (Exception ex)
                {
                    EventsLog.WriteLog("ErrorInfo" + ex.Message);
                }
                return count;
            }
        }

        public IList<ReqHelpEntity> GetReqHelpList(ReqHelpQcEntity qcmodel)
        {
            var list = new List<ReqHelpEntity>();
            var strSql = new StringBuilder();
            object obj = DBNull.Value;
            int start = qcmodel.PageSize * qcmodel.PageIndex + 1;
            int end = qcmodel.PageSize + start - 1;
            strSql.Append(" SELECT T.* FROM( ");
            strSql.Append(" SELECT row_number() over (order by A.InputTime) AS idx,A.[ReqID],C.WSID,C.WSName,A.[ETypeCode],B.ETypeName,A.[UserID],D.LoginCode,D.FullName,D.MobileNo,E.DptName FROM [UT_ReqHelp] AS A INNER JOIN UT_EType AS B ON A.ETypeCode=B.ETypeCode INNER JOIN UT_WorkShop AS C ON A.WSID=C.WSID INNER JOIN UT_User AS D ON A.UserID=D.UserID INNER JOIN UT_Department E ON D.DptID=E.DptID ");
            strSql.Append(" WHERE 1=1 ");
            if (!string.IsNullOrEmpty(qcmodel.ETypeCode))
            {
                strSql.Append(" AND A.ETypeCode ='" + qcmodel.ETypeCode + "'");
            }
            if (!string.IsNullOrEmpty(qcmodel.WSID))
            {
                strSql.Append(" AND A.WSID ='" + qcmodel.WSID + "'");
            }
            strSql.Append(") AS T ");

            strSql.Append(" Where T.idx between " + start + " and " + end);

            if (qcmodel.SortField != "" && qcmodel.SortOrder != "")
            {
                strSql.Append(" Order by " + qcmodel.SortField + " " + qcmodel.SortOrder);
            }
            using (var cmd = Db.GetSqlStringCommond(strSql.ToString()))
            {
                try
                {
                    using (IDataReader reader = Db.ExecuteReader(cmd))
                    {
                        while (reader.Read())
                        {
                            var model = new ReqHelpEntity();
                            if (reader["ReqID"] != DBNull.Value)
                                model.ReqID = new Guid(reader["ReqID"].ToString());
                            if (reader["WSID"] != DBNull.Value)
                                model.WSID = new Guid(reader["WSID"].ToString());
                            model.WSName = reader["WSName"] == obj ? null : Convert.ToString(reader["WSName"]);
                            model.ETypeCode = reader["ETypeCode"] == obj ? null : Convert.ToString(reader["ETypeCode"]);
                            model.ETypeName = reader["ETypeName"] == obj ? null : Convert.ToString(reader["ETypeName"]);
                            if (reader["UserID"] != DBNull.Value)
                                model.UserID = new Guid(reader["UserID"].ToString());
                            model.LoginCode = reader["LoginCode"] == obj ? null : Convert.ToString(reader["LoginCode"]);
                            model.FullName = reader["FullName"] == obj ? null : Convert.ToString(reader["FullName"]);
                            model.MobileNo = reader["MobileNo"] == obj ? null : Convert.ToString(reader["MobileNo"]);
                            model.DptName = reader["DptName"] == obj ? null : Convert.ToString(reader["DptName"]);
                            list.Add(model);
                        }
                    }
                }
                catch (Exception ex)
                {
                    EventsLog.WriteLog("ErrorInfo" + ex.Message);
                }
            }
            return list;
        }

        public void AddReqHelp(List<ReqHelpEntity> list)
        {
            var conn = Db.GetConnection() as SqlConnection;
            if (conn == null)
            {
                throw new InvalidOperationException("No Valid Database Connection!");
            }
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            using (var bcp = new SqlBulkCopy(conn))
            {
                var mapReqId =
                    new SqlBulkCopyColumnMapping("ReqID", "ReqID");
                bcp.ColumnMappings.Add(mapReqId);

                var mapWsid =
                    new SqlBulkCopyColumnMapping("WSID", "WSID");
                bcp.ColumnMappings.Add(mapWsid);

                var mapETypeCode =
                  new SqlBulkCopyColumnMapping("ETypeCode", "ETypeCode");
                bcp.ColumnMappings.Add(mapETypeCode);


                var mapUserId =
                    new SqlBulkCopyColumnMapping("UserID", "UserID");
                bcp.ColumnMappings.Add(mapUserId);

                bcp.DestinationTableName = "UT_ReqHelp";

                try
                {
                    bcp.WriteToServer(Collection.ToDataTable(list));
                }
                catch (Exception ex)
                {
                    EventsLog.WriteLog("ErrorInfo" + ex.Message);
                }
                finally
                {
                    if (conn.State != ConnectionState.Closed)
                        conn.Close();
                }
            }
        }

        public bool RemoveReqHelp(string id)
        {
            var result = false;
            var strSql = new StringBuilder();
            strSql.Append(" Delete From UT_ReqHelp Where ReqID=@ReqID ");
            using (DbCommand cmd = Db.GetSqlStringCommond(strSql.ToString()))
            {
                try
                {
                    Db.AddInParameter(cmd, "@ReqID", id);
                    result = Db.ExecuteNonQuery(cmd) > 0;
                }
                catch (Exception ex)
                {
                    EventsLog.WriteLog("ErrorInfo" + ex.Message);
                }
            }
            return result;
        }

        public IList<ReqHelpEntity> GetReqHelpUsers(ReqHelpQcEntity qcmodel)
        {
            var list = new List<ReqHelpEntity>();
            var strSql = new StringBuilder();
            object obj = DBNull.Value;
            strSql.Append(" SELECT A.[UserID],D.LoginCode,D.FullName,D.MobileNo,E.DptName FROM [UT_ReqHelp] AS A  INNER JOIN UT_User AS D ON A.UserID=D.UserID INNER JOIN UT_Department E ON D.DptID=E.DptID ");
            strSql.Append(" WHERE 1=1 ");
            if (!string.IsNullOrEmpty(qcmodel.ETypeCode))
            {
                strSql.Append(" AND A.ETypeCode ='" + qcmodel.ETypeCode + "'");
            }
            if (!string.IsNullOrEmpty(qcmodel.WSID))
            {
                strSql.Append(" AND A.WSID ='" + qcmodel.WSID + "'");
            }
            using (var cmd = Db.GetSqlStringCommond(strSql.ToString()))
            {
                try
                {
                    using (IDataReader reader = Db.ExecuteReader(cmd))
                    {
                        while (reader.Read())
                        {
                            var model = new ReqHelpEntity();
                            if (reader["UserID"] != DBNull.Value)
                                model.UserID = new Guid(reader["UserID"].ToString());
                            model.LoginCode = reader["LoginCode"] == obj ? null : Convert.ToString(reader["LoginCode"]);
                            model.FullName = reader["FullName"] == obj ? null : Convert.ToString(reader["FullName"]);
                            model.MobileNo = reader["MobileNo"] == obj ? null : Convert.ToString(reader["MobileNo"]);
                            model.DptName = reader["DptName"] == obj ? null : Convert.ToString(reader["DptName"]);
                            list.Add(model);
                        }
                    }
                }
                catch (Exception ex)
                {
                    EventsLog.WriteLog("ErrorInfo" + ex.Message);
                }
            }
            return list;
        }

        public bool RemoveReqHelp(Guid wsid, string eTypeCode)
        {
            var result = false;
            var strSql = new StringBuilder();
            strSql.Append(" Delete From UT_ReqHelp Where WSID=@WSID AND ETypeCode=@ETypeCode ");
            using (DbCommand cmd = Db.GetSqlStringCommond(strSql.ToString()))
            {
                try
                {
                    Db.AddInParameter(cmd, "@WSID", wsid);
                    Db.AddInParameter(cmd, "@ETypeCode", eTypeCode);
                    result = Db.ExecuteNonQuery(cmd) > 0;
                }
                catch (Exception ex)
                {
                    EventsLog.WriteLog("ErrorInfo" + ex.Message);
                }
            }
            return result;
        }
    }
}
